package com.niit.action;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSONObject;
import com.niit.common.Result;
import com.niit.service.UserService;
import com.niit.service.impl.UserServiceImpl;

/**
 * 
 */
@WebServlet("/UserServlet.do")
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UserServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		System.out.println(username + "---" + password);
		if (username == null || "".equals(username) || password == null || "".equals(password)) {
			response.sendRedirect("index.jsp");
		} else {
			// 登录逻辑
			response.setContentType("application/json");
			response.setCharacterEncoding("UTF-8");
			PrintWriter writer = response.getWriter();
			Result result = null;
			UserService userService = new UserServiceImpl();
			boolean isSuccess = userService.login(username, password);
			if (isSuccess) {
				result = Result.success("登录成功");
				HttpSession session = request.getSession();
				session.setAttribute("username", username);
			} else {
				result = Result.error("登录失败，帐号或密码错误");
			}
			// 返回JSON数据给前端
			JSONObject json = (JSONObject) JSONObject.toJSON(result);
			writer.print(json);
			writer.close();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
